package com.ruoyi.generator.util;


import com.ruoyi.system.domain.vo.OSSCertificateVo;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取Oss文件上传Token
 * Created by User on 2017/7/1.
 */
public class GetFileUploadToken {
    public static Logger logger = LoggerFactory.getLogger(GetFileUploadToken.class);

    // 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
    public static final String REGION_CN_HANGZHOU = "cn-beijing";
    // 当前 STS API 版本
    public static final String STS_API_VERSION = "2015-04-01";
    //阿里云key值
    private static String accessKeyId = "LTAI4GDSGL26Cf6aQN6wz5dZ";
    //阿里云Secret值
    private static String accessKeySecret = "3EEiEQhuNbi69ek7YR4B5NWnUs9dqr";
    //阿里云角色对象
    private static String roleArn = "acs:ram::1399152358142791:role/sumerchan";
    //角色认证对象
    private static final String  policy = "{\n" +
            "    \"Version\": \"1\", \n" +
            "    \"Statement\": [\n" +
            "        {\n" +
            "            \"Action\": [\n" +
            "                \"oss:GetBucket\", \n" +
            "                \"oss:GetObject\", \n" +
            "				  \"oss:AbortMultipartUpload\",\n"+
            "                 \"oss:PutObject\"\n"+
            "            ], \n" +
            "            \"Resource\": [\n" +
            "                \"acs:oss:*:*:*\"\n" +
            "            ], \n" +
            "            \"Effect\": \"Allow\"\n" +

            "        }\n" +
            "    ]\n" +
            "}";

    //定义返回接口对象
    private static OSSCertificateVo ossCertificateVo=null;

    /**
     * 获取阿里云接口中的上传文件权限认证接口
     * 时间 2017年7月1日16:11:00
     * @return
     */
    public static OSSCertificateVo getsTheSTSCredentials(String requestRoleSessionName){
        logger.info("getFileUploadToken.获取上传文件token指令,roleSessionName={}",requestRoleSessionName);
        String roleSessionName = "Q_0001";
        if(null!=requestRoleSessionName&&!("".equals(requestRoleSessionName.trim()))&&!("null".equals(requestRoleSessionName.trim()))){
            roleSessionName=requestRoleSessionName;
        }
        // 此处必须为 HTTPS
        com.aliyuncs.http.ProtocolType protocolType = com.aliyuncs.http.ProtocolType.HTTPS;
        try {
            final com.aliyuncs.sts.model.v20150401.AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy, protocolType);
            logger.debug("Expiration: " + response.getCredentials().getExpiration());
            logger.debug("Access Key Id: " + response.getCredentials().getAccessKeyId());
            logger.debug("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
            logger.debug("Security Token: " + response.getCredentials().getSecurityToken());
            ossCertificateVo= OSSCertificateVo.builder()
                    .expiration(response.getCredentials().getExpiration())
                    .accessKeyId(response.getCredentials().getAccessKeyId())
                    .accessKeySecret(response.getCredentials().getAccessKeySecret())
                    .securityToken(response.getCredentials().getSecurityToken()).build();

        } catch (ClientException e) {
            logger.warn("Failed to get a token.");
            logger.warn("Error code: " + e.getErrCode());
            logger.warn("Error message: " + e.getErrMsg());
        }
        return ossCertificateVo;
    }

    /**
     * 请求阿里云assumeRole接口，返回上传文件接口权限认证
     * 时间  2017年7月1日16:11:40
     * @param accessKeyId
     * @param accessKeySecret
     * @param roleArn
     * @param roleSessionName
     * @param policy
     * @param protocolType
     * @return
     * @throws ClientException
     */
    public static com.aliyuncs.sts.model.v20150401.AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,
                                                                                 String roleArn, String roleSessionName, String policy,
                                                                                 ProtocolType protocolType) throws ClientException {
        try {
            // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
            IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // 创建一个 AssumeRoleRequest 并设置请求参数
            final com.aliyuncs.sts.model.v20150401.AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(protocolType);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            // 发起请求，并得到response
            final AssumeRoleResponse response = client.getAcsResponse(request);
            return response;
        } catch (ClientException e) {
            throw e;
        }
    }
}
